package cn.wenhe9.controller;

import cn.wenhe9.domain.ResultInfo;
import cn.wenhe9.domain.User;
import cn.wenhe9.service.UserService;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService service;

    @ResponseBody
    @RequestMapping("/login")
    public ModelAndView login(User user, HttpSession session) throws JsonProcessingException {

        User result = service.login(user);

        System.out.println(result);

        ResultInfo resultInfo = new ResultInfo();
        ModelAndView modelAndView = new ModelAndView();
        if (result!=null){
            session.setAttribute("user", result);
            resultInfo.setFlag(true);
            resultInfo.setData(result);

            modelAndView.addObject("resultInfo", resultInfo);
            modelAndView.setViewName("redirect:/customer/findAll?pageNum=0");
        }else{
            resultInfo.setFlag(false);
            resultInfo.setErrMsg("用户名或密码错误");

            modelAndView.addObject("resultInfo", resultInfo);
            modelAndView.setViewName("login");
        }

        return modelAndView;
    }

    @RequestMapping("/exist")
    public String exist(HttpSession session){

        session.removeAttribute("user");

        return "login";
    }
}
